import throttle from 'function/throttle';

interface options <T extends HTMLElement> {
  el: string | T;
  offsetTop?: number;
  callback(): void;
}

export function LazyLoadingFn(options: options<HTMLDivElement>) {
  const el = typeof options.el === 'string' ? document.querySelector<HTMLDivElement>(options.el)! : options.el;
  const offsetTop = options.offsetTop ?? 200;
  const scrollHandel = throttle((event: Event) => {
    const target = event.target as HTMLDivElement;
    const { scrollTop } = target;
    const { scrollHeight } = target;

    if (scrollTop + target.clientHeight + offsetTop >= scrollHeight) {
      options.callback && options.callback.call(null);
    }
  });

  el.addEventListener('scroll', scrollHandel);
  return {
    destroy() {
      el.removeEventListener('scroll', scrollHandel);
    },
  };
}

export class LazyLoading {
  public el: HTMLDivElement;

  public offsetTop: number;

  public callback: () => void;

  constructor(options: options<HTMLDivElement>) {
    this.callback = options.callback;
    this.offsetTop = options.offsetTop || 300;
    this.el = typeof options.el === 'string' ? document.querySelector<HTMLDivElement>(options.el)! : options.el;

    this.noop = throttle<LazyLoading>(this.scrollHandel, 150);
    this.el.addEventListener('scroll', this.noop);
  }

  public scrollHandel(event: Event) {
    const target = event.target as HTMLDivElement;
    const { scrollTop } = target;
    const { scrollHeight } = target;

    if (scrollTop + target.clientHeight + this.offsetTop >= scrollHeight) {
      this.callback && this.callback.call(null);
    }
    console.log(scrollTop, target.clientHeight, scrollHeight);
  }

  private noop(event: Event) {}

  public destroy() {
    this.el.removeEventListener('scroll', this.noop);
  }
}
